package com.github.pig.admin.controller.bindowner;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pig.admin.model.entity.SysCommunityUser;
import com.github.pig.admin.model.entity.SysUserRole;
import com.github.pig.admin.model.zhgl.building.CommunityBuilding;
import com.github.pig.admin.model.zhgl.community.CommunityInfo;
import com.github.pig.admin.model.zhgl.house.UnitHouse;
import com.github.pig.admin.model.zhgl.houseowner.CurrentUserBean;
import com.github.pig.admin.model.zhgl.houseowner.HouseOwner;
import com.github.pig.admin.service.bindowner.BindOwnerService;
import com.github.pig.admin.service.sys.ISysCommunityUserService;
import com.github.pig.admin.service.sys.SysRoleService;
import com.github.pig.admin.service.sys.SysUserRoleService;
import com.github.pig.admin.service.zhgl.building.ICommunityBuildingService;
import com.github.pig.admin.service.zhgl.community.ICommunityInfoService;
import com.github.pig.admin.service.zhgl.house.IUnitHouseService;
import com.github.pig.admin.service.zhgl.houseowner.IHouseOwnerService;
import com.github.pig.admin.service.zhgl.unit.IBuildingUnitService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.bean.aop.SystemControllerLog;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 前端控制器-业主绑定小区
 * </p>
 *
 * @author xiaosa
 * @since 2018-06-04
 */
@Controller
@RequestMapping("/bindOwner")
@Slf4j
public class BindOwnerController extends BaseController {
    @Autowired
    private ICommunityInfoService communityInfoService;
    @Autowired
    private ICommunityBuildingService communityBuildingService;
    @Autowired
    private IBuildingUnitService unitService;
    @Autowired
    private IUnitHouseService houseService;
    @Autowired
    private IHouseOwnerService ownerService;
    @Autowired
    private BindOwnerService bindOwnerService;
    @Autowired
    private ISysCommunityUserService sysCommunityUserService;
    @Autowired
    private SysRoleService  sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 获取小区列表
     * @return 小区列表
     */
    @GetMapping("/communityList")
    @ResponseBody
    public List<CommunityInfo> communityInfoList() {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
        entityWrapper.orderBy("sort",true);
        return communityInfoService.selectList(entityWrapper);
    }

    /**
     * 获取当前登陆人绑定的房屋信息
     * @return
     */
    @GetMapping("/bingCommunityMessage")
    @ResponseBody
    public AjaxJson bingCommunityMessage() {
        AjaxJson json = new AjaxJson();
        try{
            json.setSuccess(true);
            //当前登陆名
            Claims claims = getCurrentUserInfo();
            String loginName = (String) claims.get("user_name");
            List<CurrentUserBean> userBean = ownerService.bingCommunityMessage(loginName);
            json.setObj(userBean);
            json.setMsg("获取成功。");
        }catch (Exception e){
            log.error("获取当前登陆人绑定房屋信息失败：",e);
            json.setMsg("获取失败。");
            json.setSuccess(false);
        }

        return  json;

    }

    /**
     * 根据小区获取楼宇列表
     * @return
     */
    @GetMapping("/buildingList")
    @ResponseBody
    public List<CommunityBuilding> buildingList( String communityId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("community_id",communityId);
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.orderBy("sort",true);
        return communityBuildingService.selectList(entityWrapper);
    }

    /**
     * 根据楼宇获取单元列表或房屋列表
     * @return
     */
    @GetMapping("/unitList")
    @ResponseBody
    public AjaxJson unitList(String buildingId) {
        AjaxJson j = new AjaxJson();
        Map<String,Object> map = new HashMap<>();
        CommunityBuilding building = communityBuildingService.selectById(buildingId);
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("building_id",buildingId);
        entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
        entityWrapper.orderBy("sort",true);
        if(building.getExistUnit()!=null&&"0".equalsIgnoreCase(building.getExistUnit())){
            map.put("existUnit","0");
            j.setAttributes(map);
            j.setObj(houseService.selectList(entityWrapper));

        }else{
            map.put("existUnit","1");
            j.setAttributes(map);
            j.setObj(unitService.selectList(entityWrapper));
        }
        return j;
    }

    /**
     * 根据单元获取房屋列表
     * @return
     */
    @GetMapping("/houseList")
    @ResponseBody
    public List<UnitHouse> houseList(String unitId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("unit_id",unitId);
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.orderBy("sort",true);
        return houseService.selectList(entityWrapper);
    }

    /**
     * 根据小区ID获取小区信息
     * @return
     */
    @GetMapping("/getCommunityInfoById")
    @ResponseBody
    public CommunityInfo getCommunityInfoById(String communityId) {
        return communityInfoService.selectById(communityId);
    }

    /**
     * 根据物业人员ID获取绑定小区信息
     * @return
     */
    @GetMapping("/getCommunityInfosByWyId")
    @ResponseBody
    public AjaxJson getCommunityInfosByWyId() {
        AjaxJson json = new AjaxJson();
        Map<String,Object> map = new HashMap<>();
        //当前登陆名
        Claims claims = getCurrentUserInfo();
        String loginName = (String) claims.get("user_name");
        UserVO vo = bindOwnerService.selectUserVoByUsername(loginName);
        List<CommunityInfo> communityInfos = communityInfoService.getCommunitysByCurrentUser(loginName);
        json.setObj(communityInfos);
        //查询是否存在默认小区
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("user_id",vo.getUserId());
        entityWrapper.eq("default_flag",CommonConstant.COMMUNITY_DEFAULT_FLAG);
        entityWrapper.setSqlSelect("id, user_id AS userId, community_id AS communityId,default_flag as  defaultFlag,(select name from community_info where id=community_id) as communityName");
        List<SysCommunityUser> sysCommunityUserList = sysCommunityUserService.selectList(entityWrapper);
        if(sysCommunityUserList!=null&&sysCommunityUserList.size()>0){
            map.put("default_flag",CommonConstant.COMMUNITY_DEFAULT_FLAG);
            map.put("default_community",sysCommunityUserList.get(0));
            json.setAttributes(map);
        }

        return  json;
    }

    /**
     * 设置物业人员默认小区
     * @return
     */
    @GetMapping("/setDefaultCommunity")
    @ResponseBody
    public AjaxJson setDefaultCommunity(String communityId,String userId) {
        AjaxJson json = new AjaxJson();
        try{
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("user_id",userId);
//            entityWrapper.eq("community_id",communityId);
            List<SysCommunityUser> sysCommunityUserList = sysCommunityUserService.selectList(entityWrapper);
            if(sysCommunityUserList!=null&&sysCommunityUserList.size()>0){
                for(SysCommunityUser sysCommunityUser:sysCommunityUserList){
                    if(sysCommunityUser.getCommunityId().equals(communityId)){
                        sysCommunityUser.setDefaultFlag(CommonConstant.COMMUNITY_DEFAULT_FLAG);
                    }else{
                        sysCommunityUser.setDefaultFlag(CommonConstant.STATUS_NORMAL);
                    }

                }
                sysCommunityUserService.updateBatchById(sysCommunityUserList);
            }
            json.setSuccess(true);
            json.setMsg("设置成功");
        }catch (Exception e){
            log.error("设置默认小区失败：",e);
            json.setSuccess(false);
            json.setMsg("设置失败，请联系维护人员。");
        }
        return  json;
    }


    /**
     * 房屋绑定
     * @param  houseOwner  实体
     * @return success/false
     */
    @RequestMapping("/bindHouse")
    @ResponseBody
    public AjaxJson add(@RequestBody HouseOwner houseOwner) {
        AjaxJson json = new AjaxJson();
        try{
            //当前登陆名
            String loginName = getUserName();
            if(StringUtils.isBlank(loginName)){
                json.setSuccess(false);
                json.setMsg("token解析失败，请重新登陆。");
                return json;
            }
            UserVO vo = bindOwnerService.selectUserVoByUsername(loginName);
            json.setSuccess(true);
            //判断绑定信息是否正确
            List<HouseOwner> result=  ownerAuthentication(json,houseOwner);
            if(result==null||result.size()==0){
                json.setSuccess(false);
                json.setMsg("信息认证失败，请核查填写的信息。");
            }else {
                HouseOwner bean = result.get(0);
                if (bean.getUserId() != 0) {
                    json.setSuccess(false);
                    json.setMsg("已经绑定成功，无需重新绑定。");
                    return json;
                }
                EntityWrapper qxbd = new EntityWrapper();
                qxbd.eq("user_id", vo.getUserId());
                qxbd.notIn("house_id", bean.getHouseId());
                List<HouseOwner> houseOwners = ownerService.selectList(qxbd);
                for (HouseOwner ho : houseOwners) {
                    ho.setDefaultHouse("0");
                }
                if (houseOwners != null && houseOwners.size() > 0) {
                    ownerService.updateBatchById(houseOwners);
                }

                bean.setDefaultHouse("1");
                bean.setUserId(vo.getUserId());
                ownerService.updateBatchById(result);
                //更新用户表类型为住户
                ownerService.updateUserType(vo.getUserId());
                json.setMsg("绑定成功。");
                if(bean.getRoleId()!=null&&StringUtils.isNotEmpty(bean.getRoleId())){
                    String[] roleIds = bean.getRoleId().split(",");
                    EntityWrapper userRole = new EntityWrapper();
                    userRole.eq("user_id",bean.getUserId());
                    userRole.eq("type",CommonConstant.USER_ROLE_TYPE_OWNER);
                    //删除
                    sysUserRoleService.delete(userRole);
                    //插入sys_user_role表
                    for(String roleId : roleIds){
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(bean.getUserId());
                        sysUserRole.setRoleId(Integer.valueOf(roleId));
                        sysUserRole.setType(CommonConstant.USER_ROLE_TYPE_OWNER);
                        sysUserRole.insert();
                    }
//                    sysUserRoleService.updateSysUserRole(bean.getUserId(),bean.getRoleId(),sysRole.getRoleId());
                }
            }
        }catch (Exception e){
            log.error("房屋绑定失败：",e);
            json.setMsg("绑定失败。");
            json.setSuccess(false);
        }

        return  json;
    }

    /**
     * 住户认证
     */
    private List<HouseOwner>  ownerAuthentication(AjaxJson json,HouseOwner houseOwner){
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("name",houseOwner.getName());
        entityWrapper.eq("phone",houseOwner.getPhone());
//        entityWrapper.eq("relation",houseOwner.getRelation());
        entityWrapper.eq("house_id",houseOwner.getHouseId());
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        return ownerService.selectList(entityWrapper);
    }

    /**
     * 物业人员认证
     */
    private List<SysCommunityUser>  wyAuthentication(HouseOwner houseOwner){
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("user_id",houseOwner.getUserId());
        entityWrapper.eq("community_id",houseOwner.getCommunityId());
        return sysCommunityUserService.selectList(entityWrapper);
    }

    /**
     * 获取当前登陆人信息
     * @return
     */
    @GetMapping("/currentUser")
    @ResponseBody
    public AjaxJson getCurrentUser() {
        AjaxJson json = new AjaxJson();
        try{
            json.setSuccess(true);
            //当前登陆名
            String loginName = getUserName();
            if(StringUtils.isNotBlank(loginName)){
                CurrentUserBean userBean = ownerService.getCurrentUserAllInfo(loginName);
                json.setObj(userBean);
                json.setMsg("获取当前登陆人信息成功。");
            }else{
                json.setMsg("获取当前登陆人信息失败,请登陆后重试。");
                json.setSuccess(false);
            }
        }catch (Exception e){
            log.error("获取当前登陆人信息失败：",e);
            json.setMsg("获取当前登陆人信息失败。");
            json.setSuccess(false);
        }

        return  json;

    }

    /**
     * 设置默认房屋
     * @return
     */
    @GetMapping("/setDefaultHouse")
    @ResponseBody
    public AjaxJson setDefaultHouse(String houseId,int userId) {
        AjaxJson json = new AjaxJson();
        json.setSuccess(false);
        if(StringUtils.isEmpty(houseId)){
            log.error("houseId为空");
            return json;
        }
        if(userId==0){
            log.error("userId为空");
            return json;
        }
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("user_id",userId);
        List<HouseOwner> houseOwners = ownerService.selectList(entityWrapper);
        if(houseOwners!=null&&houseOwners.size()>0){
            for(HouseOwner owner:houseOwners){
                if(owner.getHouseId().equalsIgnoreCase(houseId)){
                    owner.setDefaultHouse("1");
                }else{
                    owner.setDefaultHouse("0");
                }
            }
            ownerService.updateBatchById(houseOwners);
            json.setSuccess(true);

        }else{
            log.error("根据user_id："+userId+"获取业主信息失败");
            return json;
        }
        return json;
    }


    @GetMapping("propertyFeeTips")
    @ResponseBody
    public AjaxJson propertyFeeTips(String houseId){
        AjaxJson json = new AjaxJson();
        if(StringUtils.isEmpty(houseId)){
            json.setSuccess(false);
            log.error("houserId为空：");
        }
        json.setSuccess(true);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        UnitHouse unitHouse = houseService.selectById(houseId);
        int status = 0;//0:正常 1：即将到期 2:欠费
        Date endDate = null;
        try {
            if(unitHouse == null || unitHouse.getProertyEndtime()==null){
                json.setSuccess(false);
                log.error("物业费到期提醒获取房屋失败：",houseId);
                return  json;
            }
            endDate = sdf.parse(sdf.format(unitHouse.getProertyEndtime()));
            Date currentDate = sdf.parse(sdf.format(new Date()));
            if(currentDate.getTime()>endDate.getTime()){//表明已经欠费
                json.setSuccess(false);
                status = 2;
                json.setMsg("您的物业费处于欠费状态，请缴纳物业费!");
            }else{
                //判断物业费是否即将到期 5天
                Calendar calendar  = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.DAY_OF_YEAR,CommonConstant.FEE_TIP_DAY);
                Date tipDate = calendar.getTime();
                if(tipDate.getTime()>=endDate.getTime()){
                    json.setSuccess(true);
                    status = 1;
                    json.setMsg("您的物业费即将到期，请及时缴纳物业费，以免影响使用!");
                }
            }

        } catch (ParseException e) {
            json.setSuccess(false);
            log.error("获取物业费到期提醒信息失败：",e);
        }
        json.setObj(status);
        return json;
    }

    /**
     * 添加-房屋所有人
     * @param  houseOwner  实体
     * @return success/false
     */
    @RequestMapping("/doAdd")
    @ResponseBody
    @SystemControllerLog(description="添加-房屋所有人")
    public AjaxJson addOwner(@RequestBody HouseOwner houseOwner) {
        AjaxJson json=new AjaxJson();
        try{
            //判断邀请人是否已经存在
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("phone",houseOwner.getPhone());
            entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
            entityWrapper.eq("house_id",houseOwner.getHouseId());
            List result = ownerService.selectList(entityWrapper);
            if(result!=null&&result.size()>0){
                json.setSuccess(false);
                json.setMsg("该房屋下已经存在该手机号的业主信息!");
                return json;
            }
            //根据
            houseOwner.setInviteDate(new Date());
            return ownerService.invitation(houseOwner);
        }catch (Exception e){
            log.error("添加房屋所有人失败：",e);
            json.setSuccess(false);
            json.setMsg("添加失败。");
        }
        return json;
    }

    /**
     * 根据登陆人获取邀请人列表
     * @return
     */
    @GetMapping("/InviteList")
    @ResponseBody
    public List<HouseOwner> InviteList(String inviteId,String relation,String houseId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        if(CommonConstant.OWNEER_RELATION.equals(relation)){
            entityWrapper.eq("house_id",houseId);
            entityWrapper.ne("id",inviteId);
            entityWrapper.isNotNull("invite_user");

        }else{
            entityWrapper.eq("invite_user",inviteId);
        }
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        entityWrapper.orderBy("relation",true);
        entityWrapper.setSqlSelect("id, name, phone,relation,(select label from sys_dict ct where ct.type='relation' and ct.value=relation) as relationName,invite_user,(select name from house_owner er where er.id=`house_owner`.invite_user) as inviteUserName");
        return ownerService.selectList(entityWrapper);
    }

    /**
     * 撤销邀请人
     * @param  ownerId  业主ID
     * @return success/false
     */
    @RequestMapping("/deleteOwner")
    @ResponseBody
    public AjaxJson deleteOwner( String ownerId) {
        AjaxJson json=new AjaxJson();
        try{
            if(StringUtils.isNotEmpty(ownerId)){
                HouseOwner houseOwner = ownerService.selectById(ownerId);
                houseOwner.setDelFlag(CommonConstant.STATUS_DEL);
                houseOwner.setDeleteInviteDate(new Date());
                json=  ownerService.delInvitation(houseOwner);

            }else{
                log.error("接收参数ownerId为空");
                json.setSuccess(false);
                json.setMsg("撤销邀请人失败。");
            }

        }catch (Exception e){
            log.error("撤销邀请人失败：",e);
            json.setSuccess(false);
            json.setMsg("撤销邀请人失败。");
        }
        return json;
    }
}
